<script setup>
import { ref, onMounted, unref, toRaw } from 'vue'
import { queryCustomersList, preAuthUploadFile, preAuthApply } from '@/api/home'
import { getByDictType } from '@/api/common'
import YearPopover from '@/components/PersonalInfo/YearPopover.vue'
import UploadAttach from '@/components/UploadAttach/index.vue'
import PreAuthHospital from './PreAuthHospital.vue'
import { InfoCircleOutlined } from '@ant-design/icons-vue'
import { queryPolicyInfo } from '@/api/comprehensive'
import PhoneModal from '@/components/PersonalInfo/PhoneModal.vue'
import MailModal from '@/components/PersonalInfo/MailModal.vue'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
const props = defineProps({
  prAutheOpen: {
    type: Boolean,
    require: false
  },
  pageFrom: {
    tyepe: String,
    require: true
  },
  policyInfo: {
    type: Object,
    required: () => {}
  },
  hospitalInfo: {
    type: Object,
    default: () => {}
  }
})
const emit = defineEmits(['close'])

const prAutheOpen = ref(props.prAutheOpen)
// pageFrom  personal :个人主页进去 hospital:医院列表预授权按钮进入
const claimtypeOptions = ref([])
const policyyearOptions = ref([])
const serviceTypeOptions = ref([])
const currencyOptions = ref([])
const ipOpOptions = ref([])
const attachTypeOptions = ref([])
const policyInfos = ref(props.policyInfo)
const colSpan = ref(8)
const rowGutter = [32, 20]
const formRef = ref()
// 表单默认值
const formData = ref({
  serviceType2: '18',
  attachType: '09',
  memberId: policyInfos.value.member_id,
  customerId: policyInfos.value.customer_id, //用户姓名
  planTypeEName: policyInfos.value.planTypeEName,
  providerId: props.hospitalInfo?.providerId || '',
  appProviderName: props.hospitalInfo?.name || '',
  fileList: [],
  serviceType1: null,
  clinicDate: null,
  endDate: null,
  applyDays: null,
  currency: null,
  applyMoney: null
})
const rules = {
  serviceType2: [
    {
      required: true,
      message: '请选择就诊类型',
      trigger: 'blur'
    }
  ],
  memberId: [
    {
      required: true,
      message: '会员必填',
      trigger: 'blur'
    }
  ],
  customerId: [
    {
      required: true,
      message: '请选择就诊人',
      trigger: 'blur'
    }
  ],
  planTypeEName: [
    {
      required: true,
      message: '请选择计划类型',
      trigger: 'blur'
    }
  ],
  serviceType1: [{ required: true, message: '请选择IP/OP', trigger: 'blur' }],
  clinicDate: [
    {
      required: true,
      message: '请选择就诊起期',
      trigger: 'blur'
    }
  ],
  applyDays: [
    {
      pattern: /^(0|[1-9]\d*)(\.\d+)?$/,
      message: '请输入大于等于0的整数或者小数',
      trigger: 'blur'
    }
  ],
  applyMoney: [
    {
      pattern: /^(0|[1-9]\d*)(\.\d+)?$/,
      message: '请输入大于等于0的整数或者小数',
      trigger: 'blur'
    }
  ],
  preAuthReason: [
    {
      validator: (rule, value) => {
        return new Promise((resolve, reject) => {
          if (value && value.length > 500) {
            reject(new Error('备注不能超过 500 个字符'))
          } else {
            resolve()
          }
        })
      },
      trigger: 'blur'
    },
    {
      required: true,
      message: '请填写主诉/诊断/治疗方式'
    }
  ],
  appProviderName: [
    {
      required: true,
      message: '请填写或者选择医院',
      trigger: 'blur'
    }
  ],
  policyYear: [
    {
      required: true
    }
  ]
}
async function getOptions() {
  let claimtypeRes = await getByDictType({ dictType: 'claimtype' })
  let policyyearRes = await getByDictType({ dictType: 'policyyear' })
  let serviceTypeOptionsRes = await getByDictType({ dictType: 'servicetype' })
  let currencyRes = await getByDictType({ dictType: 'currency' })
  let ipOpRes = await getByDictType({ dictType: 'servicetype1' })
  let attachTypeRes = await getByDictType({ dictType: 'preauthrider' })
  if (policyyearRes.isSuccess) {
    const list = []
    policyyearRes.data &&
      policyyearRes.data.length &&
      policyyearRes.data.map((v) => {
        list.push({
          label: v.dictCName,
          value: v.dictCode
        })
      })
    policyyearOptions.value = list
  }
  if (claimtypeRes.isSuccess) {
    const list = []
    claimtypeRes.data &&
      claimtypeRes.data.length &&
      claimtypeRes.data.map((v) => {
        list.push({
          label: v.dictName,
          value: v.dictCode
        })
      })
    claimtypeOptions.value = list
  }
  if (serviceTypeOptionsRes.isSuccess) {
    const list = []
    serviceTypeOptionsRes.data &&
      serviceTypeOptionsRes.data.length &&
      serviceTypeOptionsRes.data.map((v) => {
        list.push({
          label: v.dictName,
          value: v.dictCode
        })
      })
    serviceTypeOptions.value = list
  }
  if (currencyRes.isSuccess) {
    const list = []
    currencyRes.data &&
      currencyRes.data.length &&
      currencyRes.data.map((v) => {
        list.push({
          label: v.dictName,
          value: v.dictCode
        })
      })
    currencyOptions.value = list
  }
  if (ipOpRes.isSuccess) {
    const list = []
    ipOpRes.data &&
      ipOpRes.data.length &&
      ipOpRes.data.map((v) => {
        list.push({
          label: v.dictName,
          value: v.dictCode
        })
      })
    ipOpOptions.value = list
  }
  if (attachTypeRes.isSuccess) {
    const list = []
    attachTypeRes.data &&
      attachTypeRes.data.length &&
      attachTypeRes.data.map((v) => {
        list.push({
          label: v.dictName,
          value: v.dictCode
        })
      })
    attachTypeOptions.value = list
  }
}
// 获取客户列表
const insuredList = ref([])
async function getInsuredList() {
  let res = null
  try {
    const data = {
      desensitization: '02',
      insuredId: props.policyInfo.insuredId
    }
    res = await queryCustomersList(data)
  } catch (err) {
    console.log('err', err)
  }
  if (res?.isSuccess) {
    insuredList.value = res.data
  }
}
function changeCustomerId(value) {
  fetchPolicyInfo('changeDocId')
}
// mail modal
let mailInfo = ref(null)
const mailModalVisible = ref(false)
function openMailModal(info = {}) {
  mailModalVisible.value = true
  mailInfo.value = {
    customer_id: unref(formData).customerId,
    member_id: policyInfos.value.member_id,
    ...info
  }
}

// phone modal
const phoneModalVisible = ref(false)
let phoneInfo = ref(null)
function openPhoneModal() {
  phoneModalVisible.value = true
  phoneInfo.value = {
    customer_id: unref(formData).customerId,
    member_id: policyInfos.value.member_id
  }
}
// hospitalModal
const hospitalModalVisble = ref(false)
function openHospitalModal() {
  hospitalModalVisble.value = true
}
// 获取医院信息。
function getHospitalInfo(info) {
  formData.value.appProviderName = info.name
  formData.value.providerId = info.providerId
  formRef.value.validateFields('appProviderName')
}
const policyList = ref([])
function getDoctId(type) {
  let doc_id = null
  if (type == 'init') {
    doc_id = policyInfos.value.doc_id
  } else {
    doc_id = unref(insuredList).find(
      (item) => item.customerId == unref(formData).customerId
    )?.doc_id
  }
  return doc_id
}
async function fetchPolicyInfo(type) {
  const doc_id = getDoctId(type)
  let res = null
  const data = {
    desensitization: '02',
    doc_id
  }
  try {
    res = await queryPolicyInfo(data)
  } catch (err) {
    console.log('err', err)
  }
  if (res?.isSuccess) {
    policyList.value = res?.data || []
    if (type == 'changeDocId') {
      policyInfos.value = unref(policyList)[0]
    }
  }
}

// 基本信息接口初始化
onMounted(() => {
  getOptions()
  getInsuredList()
  fetchPolicyInfo('init')
})

function close() {
  prAutheOpen.value = false
  emit('close')
}
// 文件删除触发
// function onClose(data) {
//   if (!data?.riderId) return

//   fileList.value.push({ ...data, deleted: '1' })
// }

function updateCustomInfoFun(selectYearInfo) {
  policyInfos.value = selectYearInfo
  formData.value.planTypeEName = policyInfos.value.planTypeEName //计划类型
  formData.value.insuredEffectiveDate = policyInfos.value.insuredEffectiveDate //计划类型
  formData.value.insuredExpireDate = policyInfos.value.insuredExpireDate //计划类型
  formData.value.memberId = policyInfos.value.member_id
  formData.value.customerId = policyInfos.value.customer_id
}
// 医院名称修改
function handleHospitalChange() {
  formData.value.providerId = ''
}
const loading = ref(false)
function validateHospital() {
  // 判断输入医院是否在系统中存在
  return new Promise((resolve, reject) => {
    // 判断输入医院是否在系统中存在
    if (!formData.value.providerId) {
      Modal.confirm({
        keyboard: false,
        title: '提醒',
        okText: '继续',
        cancelText: '返回',
        content: '录入的医院在系统中不存在，请确认继续下一步还是返回重新选择？',
        onOk() {
          resolve() // 验证通过，继续下一步
        },
        onCancel() {
          reject() // 验证未通过，停止流程
        }
      })
    } else {
      resolve() // 如果医院存在，直接通过
    }
  })
}
function validateInsuredStatus() {
  return new Promise((resolve, reject) => {
    // 判断当前所选被保人的生效状态是否为有效
    if (policyInfos.value.enrollmentStatus == '已过期') {
      Modal.confirm({
        keyboard: false,
        title: '提醒',
        okText: '继续',
        cancelText: '返回',
        content: '当前选择的被保人已过保期，请确认继续下一步还是返回重新选择',
        onOk() {
          resolve() // 验证通过，继续下一步
        },
        onCancel() {
          reject() // 验证未通过，停止流程
        }
      })
    } else {
      resolve() // 如果被保人状态有效，直接通过
    }
  })
}
async function onSubmit() {
  try {
    // 先表单验证
    await formRef.value.validate()
    // 先验证医院，再验证被保人状态，依次验证
    await validateHospital()
    await validateInsuredStatus()

    // 表单验证通过，执行提交逻辑
    loading.value = true
    let options = insuredList.value.find((v) => v.customerId === formData.value.customerId)
    const params = {
      ...formData.value,
      insuredId: policyInfos.value.insuredId,
      name: options.nameCn,
      clinicDate: dayjs(formData.value.clinicDate).format('YYYY-MM-DD'),
      endDate: formData.value.endDate ? dayjs(formData.value.endDate).format('YYYY-MM-DD') : '',
      fileList: formData.value.fileList.map((v) => {
        return {
          fileId: v.fileId,
          fileName: v.fileName,
          fileSuffix: v.fileSuffix,
          filePath: v.url.replace(v.fileName, ''),
          fileType: formData.value.attachType
        }
      })
    }

    let res = null
    try {
      res = await preAuthApply(params)
    } catch (error) {
      console.log('error', error)
    } finally {
      loading.value = false
    }

    if (res && res.isSuccess) {
      message.success(res.data, 1)
      loading.value = false
      formRef.value.resetFields()
      close()
    }
  } catch (error) {
    console.log('验证失败', error)
  }
}
function handleUpdate(fileList) {
  formData.value.fileList = fileList
}
</script>
<template>
  <a-drawer
    v-model:open="prAutheOpen"
    title="预授权申请"
    width="60%"
    placement="right"
    @close="close"
    :maskClosable="false"
    :footerStyle="{ textAlign: 'right' }"
    :destroyOnClose="true"
    class="preauthorization-application-drawer"
  >
    <div class="preauthorization-application">
      <a-form
        :model="formData"
        name="basic"
        layout="vertical"
        autocomplete="off"
        :rules="rules"
        ref="formRef"
      >
        <div class="item">
          <div class="item-title">就诊类型</div>
          <a-form-item label="就诊类型" name="serviceType2">
            <a-select
              v-model:value="formData.serviceType2"
              placeholder="请选择"
              class="select-width"
              :disabled="true"
              :options="serviceTypeOptions"
            >
            </a-select>
            <span class="select-tips" v-if="formData.serviceType2 == 18"
              ><InfoCircleOutlined
                class="icon-tips"
              />仅做报备，最终赔付金额以实际理赔结论为准</span
            >
          </a-form-item>
        </div>
        <div class="item">
          <div class="item-title">
            <span class="item-title-text">就诊人信息</span>
            <svg-icon name="preAuth-mail" class="icon-color" @click="openMailModal" />
            <svg-icon name="preAuth-phone" class="icon-color" @click="openPhoneModal" />
          </div>
          <a-row :gutter="rowGutter">
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item label="会员ID" name="memberId">
                <a-input v-model:value="formData.memberId" placeholder="请输入" :disabled="true" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item label="就诊人" name="customerId">
                <a-select
                  v-model:value="formData.customerId"
                  optionFilterProp="customerId"
                  style="width: 100%"
                  :field-names="{ label: 'name', value: 'customerId' }"
                  :options="insuredList"
                  @change="changeCustomerId"
                  :disabled="props.pageFrom === 'hospital'"
                >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item>
                <template #label>
                  <span style="font-size: 14px" class="label-required">保单年度</span>
                </template>
                <YearPopover
                  @updateCustomInfo="updateCustomInfoFun"
                  :info="policyInfos"
                  :policyYearList="policyList"
                  :requireGetYearList="false"
                  v-if="props.pageFrom === 'personal'"
                >
                  <div class="policy-year-box cursor-pointer mr-20">
                    <span class="policy-year">
                      {{ policyInfos.policyYear }}
                    </span>
                    <svg-icon class="arrow-year-icon" size="14" name="arrow-down" />
                  </div>
                </YearPopover>
                <a-input v-else :value="policyInfos.policyYear" disabled></a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item label="计划类型" name="planTypeEName">
                <a-input
                  v-model:value="formData.planTypeEName"
                  placeholder="请输入"
                  :disabled="true"
                />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item>
                <template #label>
                  <span style="font-size: 14px" class="label-required">被保人有效期</span>
                </template>
                <a-input
                  :value="`${policyInfos.insuredEffectiveDate} ~ ${policyInfos.insuredExpireDate}`"
                  placeholder="请输入"
                  :disabled="true"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div class="item">
          <div class="item-title">申请信息</div>
          <a-row :gutter="rowGutter">
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item label="IP/OP" name="serviceType1">
                <a-select
                  v-model:value="formData.serviceType1"
                  placeholder="请选择"
                  :options="ipOpOptions"
                >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item :rules="[{ required: true }]">
                <template #label>
                  <span style="font-size: 14px">申请医院</span>
                  <svg-icon
                    class="cursor-pointer search-icon"
                    name="home-hospital-seach"
                    size="18"
                    @click="openHospitalModal"
                    v-if="props.pageFrom === 'personal'"
                  />
                </template>
                <a-input-group compact class="compact-wraaper">
                  <a-input
                    v-model:value="formData.providerId"
                    placeholder="医院编码"
                    :disabled="true"
                    style="width: 30%"
                  />
                  <a-form-item name="appProviderName">
                    <a-tooltip :title="formData.appProviderName">
                      <a-input
                        v-model:value="formData.appProviderName"
                        @change="handleHospitalChange"
                        :disabled="props.pageFrom === 'hospital'"
                        placeholder="医院名称"
                        class="borderRadiusLeft-0"
                      />
                    </a-tooltip>
                  </a-form-item>
                </a-input-group>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item label="就诊起期" name="clinicDate">
                <a-date-picker v-model:value="formData.clinicDate" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item label="就诊止期" name="endDate">
                <a-date-picker v-model:value="formData.endDate" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item label="预估天数" name="applyDays">
                <a-input v-model:value="formData.applyDays" placeholder="预估天数" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="colSpan">
              <a-form-item label="申请金额">
                <a-input-group compact class="compact-wraaper">
                  <a-select
                    v-model:value="formData.currency"
                    placeholder="币种"
                    :options="currencyOptions"
                    style="width: 30%"
                  >
                  </a-select>
                  <a-form-item name="applyMoney">
                    <a-input
                      v-model:value="formData.applyMoney"
                      placeholder="申请金额"
                      class="borderRadiusLeft-0"
                    />
                  </a-form-item>
                </a-input-group>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="24">
              <a-form-item label="主诉/诊断/治疗方式" name="preAuthReason">
                <a-textarea
                  v-model:value="formData.preAuthReason"
                  placeholder="请输入"
                  :rows="4"
                  :maxlength="500"
                  show-count
                />
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div class="item">
          <div class="item-title">上传附件</div>
          <a-form-item label="附件类型" name="attachType">
            <a-select
              v-model:value="formData.attachType"
              placeholder="请选择"
              :disabled="true"
              style="width: 31.3333%"
              :options="attachTypeOptions"
            >
            </a-select>
          </a-form-item>
          <div class="item-form">
            <!-- @on-close="onClose" -->
            <a-form-item name="fileList">
              <UploadAttach
                v-model="formData.fileList"
                :uploadApi="preAuthUploadFile"
                @update="handleUpdate"
              />
            </a-form-item>
          </div>
        </div>
      </a-form>
    </div>
    <template #footer>
      <a-button style="margin-right: 8px" @click="close">取消</a-button>
      <a-button type="primary" @click="onSubmit" :loading="loading">提交</a-button>
    </template>
    <PhoneModal
      :phone-info="phoneInfo"
      v-if="phoneModalVisible"
      @updateVisible="(visible) => (phoneModalVisible = visible)"
      @openMailModal="openMailModal"
    ></PhoneModal>
    <MailModal
      v-if="mailModalVisible"
      :mail-info="mailInfo"
      @updateVisible="(visible) => (mailModalVisible = visible)"
    ></MailModal>
  </a-drawer>
  <PreAuthHospital
    v-if="hospitalModalVisble"
    :policyInfo="policyInfos"
    @updateVisible="(visible) => (hospitalModalVisble = visible)"
    @getHospitalInfo="getHospitalInfo"
  ></PreAuthHospital>
</template>

<style lang="scss">
.preauthorization-application-drawer {
  .ant-drawer-header-title {
    flex-direction: row-reverse;
    justify-content: space-between;
  }
}
.preauthorization-application {
  .item {
    margin-bottom: 40px;
  }
  .item-title {
    height: 14px;
    border-left: 3px solid #4d789c;
    padding-left: 11px;
    font-family: PingFang-SC, PingFang-SC;
    font-weight: bold;
    font-size: 14px;
    color: $color-text-primary;
    margin-bottom: 14px;
    // margin-top: 31px;
    display: flex;
    align-items: center;
    &-text {
      margin-right: 10px;
    }
    .icon-color {
      font-size: 14px;
      margin-right: 8px;
      cursor: pointer;
    }
  }
  .ant-form-item {
    margin-bottom: 0;
    .ant-row {
      display: block !important;
    }
    .ant-form-item-label > label {
      font-size: 14px;
      color: #333333;
      font-weight: 400;
    }
  }
  // 就诊类型输入框的样式
  .select-width {
    width: 31.33333%;
  }
  .select-tips {
    margin-left: 15px;
    font-size: 14px;
    color: #666666;
    .icon-tips {
      margin-right: 6px;
    }
  }
  .item-form {
    margin-top: 16px;
  }
  .policy-year-box {
    width: 100%;
    height: 32px;
    display: flex;
    border-radius: 6px;
    background-color: #ffffff;
    border: 1px solid #d9d9d9;
    align-items: center;
    position: relative;
    justify-content: space-between;
    padding: 0 11px;
    .policy-year {
      font-size: 14px;
      color: #333333;
    }
    .arrow-year-icon {
      color: #ccc;
    }
  }
  .ant-input-textarea-show-count::after {
    position: absolute;
    right: 13px;
    bottom: 0;
  }
}
.search-icon {
  margin-left: 10px;
}
.label-required::before {
  display: inline-block;
  margin-inline-end: 4px;
  color: #ff4d4f;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}
.compact-wraaper {
  .ant-form-item {
    width: 70%;
  }
}
.borderRadiusLeft-0 {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
</style>
